package com.project.forlearning.config;

import com.project.forlearning.dao.BackAdminMapper;
import com.project.forlearning.pojo.Admin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    BackAdminMapper backAdminMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 这里管理员默认使用管理员权限
        return new SimpleAuthorizationInfo();
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        Admin admin = backAdminMapper.queryAdmin(null, token.getUsername(), null);
        if(admin == null){
            return null; //代表账号不存在
        }else if(!admin.getAdminPass().equals(String.valueOf(token.getPassword()))){
            throw new IncorrectCredentialsException(); //代表密码错误
        }
        return new SimpleAuthenticationInfo(admin, admin.getAdminPass(), "");
    }
}
